package com.city.parking;

import com.city.parking.util.HttpClientUtil;
import com.city.parking.util.HttpRequest;
import com.city.parking.util.HttpResult;
import com.city.parking.util.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.text.Editable;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class LeaseEditActivity extends FragmentActivity implements 
        OnClickListener, OnCheckedChangeListener {
    private EditText mTitle, mPrice, mContact, mPhone, mDuration, mAddr;
    private Button mPublishBtn;
    private RadioGroup mTypeRg;
    private LeaseItem mItem = new LeaseItem();
	private final int MSG_PARKING_SERVER = 1;
    
    private final String[] mProvinceArr = {"江苏省"};
    private final String[] mCityArr = {"南京市"};
    private final String[] mDistrictArr = {"江宁区","玄武区","浦口区","栖霞区","雨花台区","白下区","秦淮区",
    		"六合区","建邺区", "鼓楼区","下关区","溧水县", "高淳县"};
    
    private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
			if (msg.what == MSG_PARKING_SERVER) {
				if (msg.arg1 == HttpRequest.NET_SUCCESS) {
					HttpResult ret = (HttpResult) msg.obj;
					if (ret.status == HttpResult.STATUS_SUCCESS) {
						ParkingApp.showToast("添加成功");
						finish();
						return;
					}
					Utils.log(ret.msg);
				}
				ParkingApp.showToast("网络错误，请稍后再试");
			}
    		mPublishBtn.setEnabled(true);
		}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_lease_edit);
        TextView titleTv = (TextView) findViewById(R.id.nav_title);
        titleTv.setText("发布租赁");

        ImageView back = (ImageView) findViewById(R.id.nav_ico_back);
        back.setOnClickListener(this);

        ImageView more = (ImageView) findViewById(R.id.nav_ico_more);
        more.setVisibility(View.GONE);

        initView();
    }

    private void initView() {
        mTitle = (EditText) findViewById(R.id.lease_title);
        mPrice = (EditText) findViewById(R.id.lease_price);
        mContact = (EditText) findViewById(R.id.lease_contact_name);
        mPhone = (EditText) findViewById(R.id.lease_contact_number);
        mDuration = (EditText) findViewById(R.id.lease_duration);
        mAddr = (EditText) findViewById(R.id.parking_addr_detail);

        mPublishBtn = (Button) findViewById(R.id.publish_lease_btn);
        mPublishBtn.setOnClickListener(this);
        mTypeRg = (RadioGroup) findViewById(R.id.lease_type_rg);
        mTypeRg.setOnCheckedChangeListener(this);
        
    	Spinner province = (Spinner) findViewById(R.id.province_spinner);
        ArrayAdapter<String> provinceAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mProvinceArr);
        provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        province.setAdapter(provinceAdapter);
        province.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
            	mItem.province = mProvinceArr[arg2];
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0){
                //
            }
        });
    	Spinner city = (Spinner) findViewById(R.id.city_spinner);
        ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mCityArr);
        cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        city.setAdapter(cityAdapter);
        city.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
                mItem.city = mCityArr[arg2];
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0){
                //
            }
        });
    	Spinner district = (Spinner) findViewById(R.id.district_spinner); 
        ArrayAdapter<String> districtAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mDistrictArr);
        districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        district.setAdapter(districtAdapter);
        district.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
                mItem.district = mDistrictArr[arg2];
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0){
                //
            }
        });
    }
    
    private void showToast(String txt) {
    	Toast.makeText(this, txt, Toast.LENGTH_SHORT).show();
    }
    
    private boolean verify() {
        String title = mTitle.getEditableText().toString();
        if (Utils.isEmptyText(title)) {
        	showToast("请输入标题");
        	mTitle.requestFocus();
        	return false;
        }
        mItem.name = title;
        
        String priceStr = mPrice.getEditableText().toString();
        if (Utils.isEmptyText(priceStr)) {
        	showToast("请输入价格");
        	mPrice.requestFocus();
        	return false;
        }
        mItem.price = Double.parseDouble(priceStr);
 
        String contact = mContact.getEditableText().toString();
        if (Utils.isEmptyText(contact)) {
        	showToast("请输入您的称呼");
        	mContact.requestFocus();
        	return false;
        }
        mItem.contact = contact;

        String phone = mPhone.getEditableText().toString();
        if (Utils.isEmptyText(phone)) {
        	showToast("请输入联系电话");
        	mPhone.requestFocus();
        	return false;
        }
        mItem.phone = phone;
        
        String duration = mDuration.getEditableText().toString();
        if (Utils.isEmptyText(duration)) {
        	showToast("请输入租期");
        	mDuration.requestFocus();
        	return false;
        }
        try {
        	mItem.duration = Integer.parseInt(duration);
        } catch (Exception e) {
        	showToast("租期请输入数字");
        	e.printStackTrace();
        	return false;
        }

        String addr = mAddr.getEditableText().toString();
        if (Utils.isEmptyText(addr)) {
        	showToast("请输入详细地址");
        	mAddr.requestFocus();
        	return false;
        }
        mItem.street = addr;

        mItem.date = Utils.getCurrentTime();
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.nav_ico_back:
            finish();
            break;
        case R.id.publish_lease_btn:
        	if (verify()) {
        		String json = mItem.toJsonStr();
        		Utils.log(json);
        		HttpRequest req = new HttpRequest(ParkingApp.url_insert_carport, MSG_PARKING_SERVER, json, mHandler);
        		HttpClientUtil.post(req);
        		mPublishBtn.setEnabled(false);
        	}
            break;

        default:
            break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup arg0, int idx) {
        // TODO Auto-generated method stub
        switch (idx) {
        case R.id.lease_in_rb:
            mItem.isOut = false;
            break;
        case R.id.lease_out_rb:
            mItem.isOut = true;
            break;
        }
    }

}
